package com.app.qtjk.lsh.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.app.common.dataDictionary.DE.DE_DEVICELASTCHANGETIME;
import com.app.common.dataDictionary.DE.DE_DEVICESFCHANGED;
import com.app.common.dataDictionary.DE.DE_OPPTIME;
import com.app.common.dataDictionary.DE.DE_PHONEIMEI;
import com.app.common.dataDictionary.DE.DE_PHONENUMBER;
import com.app.common.dataDictionary.DE.DE_PHONETYPE;
import com.app.common.dataDictionary.DE.DE_RECOMMENDCODE;
import com.app.common.dataDictionary.DE.DE_REGTIME;
import com.app.common.dataDictionary.DE.DE_USERBRANDCLICKS;
import com.app.common.dataDictionary.DE.DE_USEREMAIL;
import com.app.common.dataDictionary.DE.DE_USERID;
import com.app.common.dataDictionary.DE.DE_USERPASSWORD;
import com.app.common.dataDictionary.DE.DE_USERWEALTH;
import com.app.common.dataDictionary.PO.TUserPO;
import com.app.common.utils.CollectionUtil;
import com.app.common.utils.DateFormatUtil;
import com.app.common.utils.FilterUtil;
import com.app.common.utils.MD5Util;
import com.app.common.utils.ParamConfig;
import com.app.common.utils.PasswordCreateUtil;
import com.app.common.utils.ReqJsonUtil;
import com.app.common.utils.StringUtil;
import com.app.common.utils.mail.MailSenderFactory;
import com.app.common.utils.mail.SimpleMail;
import com.app.common.utils.mail.SimpleMailSender;
import com.css.sword.kernel.base.annotation.Service;
import com.css.sword.kernel.base.annotation.ServiceContainer;
import com.css.sword.kernel.base.persistence.IPersistenceService;
import com.css.sword.kernel.base.persistence.SQLParam;
import com.css.sword.kernel.utils.SwordLogUtils;
import com.css.sword.kernel.utils.SwordPersistenceUtils;
import com.css.sword.kernel.utils.SwordSequenceUtils;
import com.css.sword.kernel.utils.SwordServiceUtils;
import com.css.sword.platform.web.event.IReqData;
import com.css.sword.platform.web.event.IResData;
import com.css.sword.platform.web.event.SwordRes;

@ServiceContainer
public class UserService {

	private static SwordLogUtils log = SwordLogUtils
			.getLogger(UserService.class);

	public UserService() throws Exception {
		super();
	}

	/**
	 * 登录时检查是否注册，包括检查是否是注册时绑定设备,仅android设备
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserService_checkRegister")
	public IResData checkRegister(IReqData req) throws Exception {

		log.debug("开始进入 UserService_checkRegister 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		// 获取前台post的数据
		String phoneimei = ReqJsonUtil.getPostParam(req,"phoneimei");
		String phoneType = ReqJsonUtil.getPostParam(req,"phonetype");
		String useremail = ReqJsonUtil.getPostParam(req,"useremail");
		boolean registerState = false;
		boolean deviceState = true;
		SQLParam param = new SQLParam();
		param.addParam(useremail);
		//检查用户是否存在
		Map<String, Object> map2 = dao.queryMapByKey("UserService_checkRegisterUserEmail", param);
		if (CollectionUtil.isNotBlankMap(map2)) {
			registerState = true;
		}
		//检查绑定设备是否正确
		if (registerState == true) {
			String phoneTypeB = StringUtil.parse2String(map2.get("phonetype"));
			if (phoneType.equals(phoneTypeB)) {
				if (phoneType.equals("android")) {
					String phoneimeiB = StringUtil.parse2String(map2.get("phoneimei"));
					if (phoneimei.equals(phoneimeiB)) {
						deviceState = true;//与绑定设备一样(android未换设备)
					}else {
						deviceState = false;//与绑定设备不一样(android换设备)
					}
				}
			} else {
				deviceState = false;//与绑定设备不一样(类型)
			}
		}
		
		res.put("deviceState", deviceState);
		res.put("registerState", registerState);
		return res;
	}
	
	
	/**
	 * 登录时检查是否注册，包括检查是否是注册时绑定设备,仅ios设备
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserService_checkRegisterIos")
	public IResData checkRegisterIos(IReqData req) throws Exception {
		
		log.debug("开始进入 UserService_checkRegisterIos 方法。");
		
		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		
		IResData res = new SwordRes();
		// 获取前台post的数据
		String phoneType = ReqJsonUtil.getPostParam(req,"phonetype");
		String useremail = ReqJsonUtil.getPostParam(req,"useremail");
		boolean registerState = false;
		boolean deviceState = true;
		SQLParam param = new SQLParam();
		param.addParam(useremail);
		//检查用户是否存在
		Map<String, Object> map2 = dao.queryMapByKey("UserService_checkRegisterUserEmail", param);
		if (CollectionUtil.isNotBlankMap(map2)) {
			registerState = true;
		}
		//检查绑定设备是否正确
		if (registerState == true) {
			String phoneTypeB = StringUtil.parse2String(map2.get("phonetype"));
			if (phoneType.equals(phoneTypeB)) {
				deviceState = true;//ios时与绑定设备类型一样
			} else {
				deviceState = false;//ios时与绑定设备类型不一样
			}
		}
		
		res.put("deviceState", deviceState);
		res.put("registerState", registerState);
		return res;
	}
	
	
	/**
	 * 检查登录密码是否正确
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserService_checkPassword")
	public IResData checkPassword(IReqData req) throws Exception {

		log.debug("开始进入 UserService_checkPassword 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		boolean verifyPWD=false;
		// 获取前台post的数据
		String useremail = ReqJsonUtil.getPostParam(req,"useremail");
		String userPassword = ReqJsonUtil.getPostParam(req,"userPassword");
		SQLParam param = new SQLParam();
		param.addParam(useremail);
		Map<String, Object> map = dao.queryMapByKey("UserService_getUserPwByEmail", param);
		String md5pwd = MD5Util.MD5(StringUtil.parse2String(map.get("userpassword"))+MD5Util.diyStr);
		if (md5pwd.equals(userPassword)) {
			verifyPWD = true;
			String userid = StringUtil.parse2String(map.get("userid"));
			res.put("userid", userid);
		}
		res.put("verifyPWD", verifyPWD);
		
		return res;
	}	
	
	/**
	 * 用户更新绑定设备
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@Service(serviceName = "UserService_updateDevice")
	public IResData updateDevice(IReqData req) throws Exception {

		log.debug("开始进入 UserService_updateDevice 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		// 获取前台post的数据
		String useremail = ReqJsonUtil.getPostParam(req,"useremail");
		String phonetype = ReqJsonUtil.getPostParam(req,"phonetype");
		String phoneimei = ReqJsonUtil.getPostParam(req,"phoneimei");
		IResData res = new SwordRes();
		boolean deviceAndroidSfExist = false;
		boolean deviceSfkChange = false;
		boolean deviceChanged = false;
		try {
			SQLParam param = new SQLParam();
			param.addParam(useremail);
			TUserPO tUserPO = dao.queryPOByKey("UserService_getUserPOByEmail", param, TUserPO.class);
			//限定用户一个月只可以更新一次设备
			int nowDateQuot = DateFormatUtil.getNowDateQuot(DateFormatUtil.date2str(tUserPO.getDevicelastchangetime().value,DateFormatUtil.DATE_FORMAT));
			if (tUserPO.getDevicesfchanged().value == 0) {
				deviceSfkChange = true;
			} else if (tUserPO.getDevicesfchanged().value == 1){
				if (nowDateQuot > 30 ) {
					deviceSfkChange = true;
				} else {
					deviceSfkChange = false;
				}
			}
			if (deviceSfkChange == true) {
				if ("android".equals(phonetype)) {
					param.clearParams();
					param.addParam(phoneimei);
					Map<String, Object> mapByKey = dao.queryMapByKey("UserService_checkRegisterPhoneIMEI", param);
					if (CollectionUtil.isNotBlankMap(mapByKey)) {
						deviceAndroidSfExist=true;
					}
				}
				if ("ios".equals(phonetype) || deviceAndroidSfExist==false) {
					tUserPO.setPhoneimei(new DE_PHONEIMEI(phoneimei));
					tUserPO.setPhonetype(new DE_PHONETYPE(phonetype));
					tUserPO.setDevicesfchanged(new DE_DEVICESFCHANGED(1));
					tUserPO.setDevicelastchangetime(new DE_DEVICELASTCHANGETIME(DateFormatUtil.getNowDate()));
					dao.updatePO(tUserPO);
					deviceChanged = true;
				}
			}else {
				deviceChanged = false;
			}
		} catch (Exception e) {
			log.error("更新用户的绑定设备时出错！");
			e.printStackTrace();
		}
		
		res.put("deviceAndroidSfExist", deviceAndroidSfExist);
		res.put("deviceSfkChange", deviceSfkChange);
		res.put("deviceChanged", deviceChanged);
		return res;
	}	
	
	/**
	 * 用户注册接口
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Service(serviceName = "UserService_register")
	public IResData register(IReqData req) throws Exception {

		log.debug("开始进入 UserService_register 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		dao.getTransactionService().setAutoCommit(false);

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		boolean flag = true;
		try {
			// 获取前台post的参数  6个参数，6个值
			String phoneimei = ReqJsonUtil.getPostParam(req, "phoneimei");
			String phonenumber = ReqJsonUtil.getPostParam(req, "phonenumber");
			String phoneType = ReqJsonUtil.getPostParam(req, "phonetype");
			String useremail = ReqJsonUtil.getPostParam(req, "useremail");
			String userPassword = ReqJsonUtil.getPostParam(req, "userPassword");
			String recommendCode = ReqJsonUtil.getPostParam(req, "recommendCode");

			if (FilterUtil.checkToken(req) == false) {
				hashMap.put("returnStatus", "false");
				hashMap.put("msg", "请求口令错误！");
				flag = false;
			}
			if (flag == true && "android".equals(phoneType) && "".equals(phoneimei)) {
				hashMap.put("registerSuccess", "imeiIsNull");
				hashMap.put("returnStatus", "true");
				hashMap.put("msg", "手机串号为空，不能注册！");
				flag = false;
			}
			SQLParam param = new SQLParam();
			if (flag == true) {
				param.clearParams();
				param.addParam(useremail);
				Map<String, Object> map2 = dao.queryMapByKey("UserService_checkRegisterUserEmail", param);
				if (CollectionUtil.isNotBlankMap(map2)) {
					hashMap.put("registerSuccess", "emailRegisted");
					hashMap.put("returnStatus", "true");
					hashMap.put("msg", "该邮箱已注册！");
					flag = false;
				}
			}
			if (flag == true) {
				param.clearParams();
				param.addParam(phoneimei);
				Map<String, Object> map1 = dao.queryMapByKey("UserService_checkRegisterPhoneIMEI", param);
				if ("android".equals(phoneType) && CollectionUtil.isNotBlankMap(map1)) {
					hashMap.put("registerSuccess", "deviceRegisted");
					hashMap.put("returnStatus", "true");
					hashMap.put("msg", "该设备已注册！");
					flag = false;
				}
			}
			if (flag == true) {
				// 获得后台配置的用户注册后初始化的财富值
				int userWealthInitValue = (Integer) dao.queryColumnByKey("AppParamManageService_getParamValue", null, 2);
				try {
					//注册新的用户
					TUserPO tUserPO = new TUserPO();
					tUserPO.setUserid(new DE_USERID(SwordSequenceUtils.generateRandomString()));
					tUserPO.setPhoneimei(new DE_PHONEIMEI(phoneimei));
					tUserPO.setUseremail(new DE_USEREMAIL(useremail));
					tUserPO.setUserpassword(new DE_USERPASSWORD(userPassword));
					tUserPO.setPhonenumber(new DE_PHONENUMBER(phonenumber));
					tUserPO.setRecommendcode(new DE_RECOMMENDCODE(useremail));
					tUserPO.setUserwealth(new DE_USERWEALTH(userWealthInitValue));
					tUserPO.setUserbrandclicks(new DE_USERBRANDCLICKS(userWealthInitValue));
					tUserPO.setRegtime(new DE_REGTIME(new Date()));
					tUserPO.setDevicesfchanged(new DE_DEVICESFCHANGED(0));
					tUserPO.setDevicelastchangetime(new DE_DEVICELASTCHANGETIME(new Date()));
					tUserPO.setOpptime(new DE_OPPTIME(new Date()));
					tUserPO.setPhonetype(new DE_PHONETYPE(phoneType));
					dao.insertPO(tUserPO);
					//根据推荐码给相应的人加财富值
					param.clearParams();
					param.addParam(recommendCode);
					TUserPO tUserPO2 = dao.queryPOByKey("UserService_getUserPOByRC", param, TUserPO.class);
					if (tUserPO2 != null) {
						tUserPO2.setUserwealth(new DE_USERWEALTH(tUserPO2.getUserwealth().value + 2));
						dao.updatePO(tUserPO2);
					}
					hashMap.put("registerSuccess", "true");
					hashMap.put("userId", tUserPO.getUserid().value);
					hashMap.put("returnStatus", "true");
					hashMap.put("msg", "注册成功！");
					dao.commitAll();
				} catch (Exception e) {
					dao.rollbackAll();
					log.debug("---------------用户注册时发生数据库插入异常！---------------");
					e.printStackTrace();
					hashMap.put("registerSuccess", "false");
					hashMap.put("returnStatus", "true");
					hashMap.put("msg", "注册失败,用户注册时出现数据库操作异常！");
				}
			}
		} catch (Exception e) {
			dao.rollbackAll();
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "系统异常！");
		} finally {
			// 将数据添加返回
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;
	}

	/**
	 * 用户忘记密码
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Service(serviceName = "UserService_forgetPassword")
	public IResData forgetPassword(IReqData req) throws Exception {

		log.debug("开始进入 UserService_forgetPassword 方法。");
		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		IResData res = new SwordRes();
		boolean flag = true;
		try {
			// 获取前台post的数据
			String useremail = ReqJsonUtil.getPostParam(req, "useremail");
			if (FilterUtil.checkToken(req) == false) {
				hashMap.put("returnStatus", "false");
				hashMap.put("msg", "请求口令错误！");
				flag = false;
			}
			if (flag == true) {
				hashMap.put("returnStatus", "true");
				SQLParam param = new SQLParam();
				param.clearParams();
				param.addParam(useremail);
				Map<String, Object> map2 = dao.queryMapByKey("UserService_checkRegisterUserEmail", param);
				if (CollectionUtil.isBlankMap(map2)) {
					hashMap.put("userExist", "false");
					hashMap.put("msg", "该邮箱用户不存在！");
					flag = false;
				} else {
					hashMap.put("userExist", "true");
					flag = true;
				}
			}
			if (flag == true) {
				hashMap.put("returnStatus", "true");
				SimpleMailSender sender = MailSenderFactory.getSender();
				SimpleMail simpleMail = new SimpleMail();
				simpleMail.setSubject(ParamConfig.getInstanse().getParam("mailSubject"));
				String createPassWord = PasswordCreateUtil.createPassWord(6);
				simpleMail.setContent(ParamConfig.getInstanse().getParam("mailContent")+createPassWord);
				try {
					SQLParam param = new SQLParam();
					param.addParam(useremail);
					TUserPO tUserPO=dao.queryPOByKey("UserService_getUserPOByEmail", param, TUserPO.class);
					tUserPO.setUserpassword(new DE_USERPASSWORD(createPassWord));
					tUserPO.setOpptime(new DE_OPPTIME(DateFormatUtil.getNowDate()));
					dao.updatePO(tUserPO);
					sender.send(useremail, simpleMail);
					hashMap.put("emailSent", "true");
				} catch (Exception e) {
					hashMap.put("emailSent", "false");
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "系统异常！");
		} finally {
			// 将数据添加返回
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}

		return res;
	}
	
	/**
	 * 用户修改密码
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Service(serviceName = "UserService_modifyPassword")
	public IResData modifyPassword(IReqData req) throws Exception {

		log.debug("开始进入 UserService_modifyPassword 方法。");
		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		IResData res = new SwordRes();
		boolean flag = true;
		try {
			// 获取前台post的数据
			String useremail = ReqJsonUtil.getPostParam(req, "useremail");
			String userNewPassword = ReqJsonUtil.getPostParam(req, "userNewPassword");
			if (FilterUtil.checkToken(req) == false) {
				hashMap.put("returnStatus", "false");
				hashMap.put("msg", "请求口令错误！");
				flag = false;
			}
			if (flag == true) {
				hashMap.put("returnStatus", "true");
				//调用检查密码是否正确
				res = (IResData) SwordServiceUtils.callService("UserService_checkPassword", req);
				if ((Boolean) res.get("verifyPWD") == true) {
					hashMap.put("passwordState", "true");
					try {
						SQLParam param = new SQLParam();
						param.addParam(useremail);
						TUserPO tUserPO=dao.queryPOByKey("UserService_getUserPOByEmail", param, TUserPO.class);
						tUserPO.setUserpassword(new DE_USERPASSWORD(userNewPassword));
						tUserPO.setOpptime(new DE_OPPTIME(DateFormatUtil.getNowDate()));
						dao.updatePO(tUserPO);
						hashMap.put("passwordChanged", "true");
					} catch (Exception e) {
						hashMap.put("passwordChanged", "false");
						hashMap.put("msg", "修改密码失败,请重试！");
					}
				} else {
					hashMap.put("passwordState", "false");
					hashMap.put("msg", "原密码不正确,请重试！");
				}
			}
		} catch (Exception e) {
			log.debug("---------------系统发生异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "系统异常！");
		} finally {
			// 将数据添加返回
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}

		return res;
	}
	
	/**
	 * 查看个人信息,我的
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Service(serviceName = "UserService_personalInfo")
	public IResData personalInfo(IReqData req) throws Exception {

		log.debug("开始进入 UserService_personalInfo 方法。");

		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();

		IResData res = new SwordRes();
		HashMap commonMap = new HashMap();
		ArrayList commonList = new ArrayList();
		HashMap hashMap = new HashMap();
		int minDay = 0;
		try {
			SQLParam sqlParam = new SQLParam();
			// 获取前台post的数据
			String userId = ReqJsonUtil.getPostParam(req, "userId");
			sqlParam.addParam(userId);
			Map<String, Object> userInfoMap = dao.queryMapByKey("UserService_getPersonalInfo", sqlParam);
			List<Map<String, Object>> userPrizeMapList = dao.queryMapListByKey("UserService_getUserPrizeList", sqlParam);
			ArrayList<Integer> list = new ArrayList<Integer>();
			for (int i = 0; i < userPrizeMapList.size(); i++) {
				int userprizeExpirydate = (Integer) userPrizeMapList.get(i).get("userprizeExpirydate");
				Date userprizeDuihuantime = (Date) userPrizeMapList.get(i).get("userprizeDuihuantime");
				//计算用户兑换后奖品的有效天数，是动态的（与当前时间作对比计算出来的）
				String userprizeDuihuantimestr = DateFormatUtil.date2str(userprizeDuihuantime,DateFormatUtil.DATE_FORMAT);
				int quotInt = DateFormatUtil.getNowDateQuot(userprizeDuihuantimestr);
				int userprize_validity = userprizeExpirydate - quotInt;
				list.add(userprize_validity);
			}
			if (CollectionUtil.isNotBlankList(userPrizeMapList)) {
				minDay = Collections.min(list);
			}
			userInfoMap.put("minDay", minDay);
			commonMap.put("userInfoMap", userInfoMap);
			hashMap.put("returnStatus", "true");
			hashMap.put("msg", "成功返回，未出现异常！");
		} catch (Exception e) {
			log.debug("---------------系统异常！---------------");
			e.printStackTrace();
			hashMap.put("returnStatus", "false");
			hashMap.put("msg", "出现异常！");
		} finally {
			commonMap.put("commonData", hashMap);
			commonList.add(commonMap);
			res.addListWithDataName("returnData", commonList);
		}
		return res;

	}

}